// VideoWindow.cpp : implementation file
//

#include "stdafx.h"
#include "DesktopClient.h"
#include "VideoWindow.h"
#include "LogFileWriter.h"

char *CStrFromWSTR(UINT codePage, LPCWSTR wstr, UINT len)
{
	if (len > 0)
	{
		size_t mblen = WideCharToMultiByte(codePage,
			0, wstr, len, NULL, 0, NULL, NULL);
		if (mblen > 0)
		{
			char *buffer = (char *)CoTaskMemAlloc(mblen+1);
			ZeroMemory(buffer, mblen+1);
			if (WideCharToMultiByte(codePage, 0, wstr, len, buffer, mblen, NULL, NULL))
			{
				buffer[mblen] = '\0';
				return buffer;
			}
		}
	}
	return NULL;
};

char *CStrFromBSTR(UINT codePage, BSTR bstr)
{
	return CStrFromWSTR(codePage, bstr, SysStringLen(bstr));
};


IMPLEMENT_DYNAMIC(CVideoWindow, CWnd)
NVR_RAW_IMAGE*	CVideoWindow::m_nvrRawImageList[MAX_DVR_CHANNEL]={0,};
int*		CVideoWindow::nvrVideoListIndexs[MAX_DVR_CHANNEL]={0,};

HANDLE CVideoWindow::m_hMapFile = NULL;
HANDLE CVideoWindow::m_hMapFileHeader = NULL;
bool	CVideoWindow::m_bfirsttime = true;
CVideoWindow::CVideoWindow()
{
	t0 = ::GetTickCount();
	m_bEnableDigitalZoom = FALSE;
	i_frames = 0;
	prev_fps = 0;
	m_bCaptured = false;
	m_pCaptureBuffer = NULL;
	m_nBufferSize = 0;

	m_pRefImage = NULL;
	m_pRGBBuffer = NULL;
//	ownerCameraInfo = NULL;
	m_bAVIFileEnable = false;
	m_bOverlay = false;
	i_img_width = 0;
	i_img_height = 0;
	i_chroma = 0;
	b_chroma = 0; /* Force a specific chroma on the dshow input */

	nvrRawImage = 0;
	i_prev_atimestamp = 0;
	i_prev_vtimestamp = 0;
	videoInIndex = 1;
	videoListIndex = 0 ; // video list index
	memset(_c_ownerStateStr, 0, sizeof(_c_ownerStateStr));

	m_nGetLength = 0;
#if 0
	m_OSDFont.lfHeight =-13; 
	m_OSDFont.lfWidth =0;
	m_OSDFont.lfEscapement=0; 
	m_OSDFont.lfOrientation=0; 
	m_OSDFont.lfWeight=FW_NORMAL; 
	m_OSDFont.lfItalic=FALSE; 
	m_OSDFont.lfUnderline=FALSE; 
	m_OSDFont.lfStrikeOut=0; 
	m_OSDFont.lfCharSet=ANSI_CHARSET; 
	m_OSDFont.lfOutPrecision=OUT_OUTLINE_PRECIS; 
	m_OSDFont.lfClipPrecision=CLIP_DEFAULT_PRECIS; 
	m_OSDFont.lfQuality=DEFAULT_QUALITY; 
	m_OSDFont.lfPitchAndFamily=DEFAULT_PITCH | FF_SWISS; 
	swprintf(m_OSDFont.lfFaceName,_T("Arial")); //_T("Arial"));
#endif
	m_OSDCenterFont.lfHeight =-27; 
	m_OSDCenterFont.lfWidth =0; 
	m_OSDCenterFont.lfEscapement=0; 
	m_OSDCenterFont.lfOrientation=0; 
	m_OSDCenterFont.lfWeight=FW_NORMAL; 
	m_OSDCenterFont.lfItalic=FALSE; 
	m_OSDCenterFont.lfUnderline=FALSE;
	m_OSDCenterFont.lfStrikeOut=0; 
	m_OSDCenterFont.lfCharSet=ANSI_CHARSET; 
	m_OSDCenterFont.lfOutPrecision=OUT_OUTLINE_PRECIS; 
	m_OSDCenterFont.lfClipPrecision=CLIP_DEFAULT_PRECIS; 
	m_OSDCenterFont.lfQuality=DEFAULT_QUALITY; 
	m_OSDCenterFont.lfPitchAndFamily=DEFAULT_PITCH | FF_SWISS; 
	swprintf(m_OSDCenterFont.lfFaceName, 5, _T("Arial")); //_T("Arial"));
	wmemset(videoName, 0, 200);
	wmemset(recordingStatus, 0, 30);
	wmemset(motionStatus, 0, 30);
	wmemset(audioStatus, 0, 30);
	wmemset(ptzStatus, 0, 30);
	wmemset(centerStr, 0, 30);
	wmemset(dateTimeStr, 0, 30);

	wsprintf(videoName,_T(""));
	wsprintf(recordingStatus,_T("Disable"));
	wsprintf(motionStatus,_T("Disable"));
	wsprintf(audioStatus,_T("Disable"));
	wsprintf(ptzStatus,_T("Disable"));
	wsprintf(centerStr,_T(""));
	wsprintf(dateTimeStr,_T(""));
	m_OSDColor = 0xffffff;
	m_pAudioPlayer = NULL;

	m_nCreateBy = 0;

	if (m_bfirsttime)
	{
		m_bfirsttime = false;

		if (m_hMapFileHeader == NULL)
		{
			m_hMapFileHeader = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, _T("Global\\VIDEO_LIST_INDEX_MAP"));
			if (m_hMapFileHeader == NULL)
			{
				m_bfirsttime = true;
				__DEBUG("cannot open Shared MEMORY");
				return;
			}
			else
			{
				int*	nvrVideoListAddress;
				//nvrVideoListAddress = (int*)MapViewOfFile(m_hMapFileHeader, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, MAX_FIRST_MEMORY_SIZE);
				nvrVideoListAddress = (int*)MapViewOfFile(m_hMapFileHeader, FILE_MAP_READ , 0, 0, MAX_FIRST_MEMORY_SIZE);
				if (nvrVideoListAddress == NULL)
				{
					__DEBUG("nvrVideoListAddress in NULL");
					if (m_hMapFileHeader)
					{
						m_bfirsttime = true;
						CloseHandle(m_hMapFileHeader);
						m_hMapFileHeader = NULL;
					}
					return;
				}

				int j=0;
				for (j=0; j<MAX_DVR_CHANNEL; j++)
					nvrVideoListIndexs[j] = (int*) (nvrVideoListAddress + j);
			}
		}

		if (m_hMapFile == NULL)
		{
			m_hMapFile = OpenFileMapping(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, _T("Global\\RAWIMAGE_LIST_MAP"));

			if (m_hMapFile == NULL)
			{
				__DEBUG("cannot open Shared MEMORY");
				return;
			}
			else
			{
				//NVR_RAW_IMAGE** rawImageListAddress = (NVR_RAW_IMAGE**)MapViewOfFile(m_hMapFile, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, MAX_MEMORY_MAP);
				NVR_RAW_IMAGE** rawImageListAddress = (NVR_RAW_IMAGE**)MapViewOfFile(m_hMapFile, FILE_MAP_READ, 0, 0, MAX_MEMORY_MAP);
				if (rawImageListAddress == NULL)
				{
					__DEBUG("rawImageListAddress in NULL");
					//2011-07-26, Cricket Added
					if (m_hMapFile)
					{
						m_bfirsttime = true;
						CloseHandle(m_hMapFile);
						m_hMapFile = NULL;
					}
					return;
				}
				for (int i = 0; i < MAX_DVR_CHANNEL; i++)
				{
					m_nvrRawImageList[i] = (NVR_RAW_IMAGE*) ((unsigned char*)rawImageListAddress + (i * sizeof(NVR_RAW_IMAGE)));
				}
			}
		}
	}
	m_needPause = false;
}

CVideoWindow::~CVideoWindow()
{
	if (m_pCaptureBuffer)
		delete[] m_pCaptureBuffer;
	if (m_pRefImage)
		delete[] m_pRefImage;
	if (m_pRGBBuffer)
		delete[] m_pRGBBuffer;
	if (&bkgndBrush)
		DeleteObject(bkgndBrush);
}


BEGIN_MESSAGE_MAP(CVideoWindow, CWnd)
	ON_WM_CREATE()
	ON_WM_SIZE()
	ON_WM_ERASEBKGND()
	ON_WM_PAINT()
	ON_WM_MBUTTONDBLCLK()
	ON_WM_LBUTTONDBLCLK()
	ON_WM_LBUTTONUP()
	//	ON_WM_RBUTTONUP()
	ON_WM_MOUSEMOVE()
	ON_WM_TIMER()
	ON_WM_DESTROY()
END_MESSAGE_MAP()



// CVideoWindow message handlers
int CVideoWindow::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	RECT rcWnd;
	rcWnd.left =0;
	rcWnd.top = 0;
	rcWnd.right = lpCreateStruct->cx;
	rcWnd.bottom = lpCreateStruct->cy;
	if (CWnd::OnCreate(lpCreateStruct) == -1)
		return -1;

	RECT rcVideo;
	RECT rcStatus;
	HWND hWnd = this->GetSafeHwnd();
	rcVideo = rcWnd;
	rcStatus = rcWnd;
	// 	rcVideo.bottom -= 20;
	// 	rcStatus.top = rcWnd.bottom - 20; 

	if (m_VideoWindow.Create(_T(""), WS_CHILD | WS_VISIBLE | SS_SIMPLE, CRect(rcVideo), this, this->GetDlgCtrlID() + 0x100))
	{
		hWnd = m_VideoWindow.GetSafeHwnd();
	}

	if (hWnd)
	{
		dDraw.SetFitArea(TRUE);
		dDraw.InitDirectDraw(hWnd, false);
		bkgndBrush.CreateSolidBrush(RGB(0,0,0)); //dDraw.GetBkGroundColor());
	}

	//	m_StatusWindow.Create(_T(""), WS_CHILD|WS_VISIBLE|SS_SIMPLE, CRect(rcStatus), this, this->GetDlgCtrlID() + 0x101);
	m_nGetLength = 0;

	//SetTimer(0x100, 300, NULL);

	return 0;
}

void CVideoWindow::OnSize(UINT nType, int cx, int cy)
{
	CWnd::OnSize(nType, cx, cy);
	CRect rcWnd;
	this->GetClientRect(&rcWnd);
	if (m_VideoWindow.GetSafeHwnd())
	{
		m_VideoWindow.MoveWindow(0,0,cx, cy, TRUE);
		CDC * pDC = m_VideoWindow.GetDC();
		CRect rect;
		m_VideoWindow.GetClientRect(&rect);
		pDC->FillRect(&rect, &bkgndBrush);
		m_VideoWindow.ReleaseDC(pDC);
	}

	dDraw.DDrawOnSize(nType, cx, cy);

	//DrawStatus();
	RECT rcDst;
	GetZoomWndRect(&rcDst);
	dDraw.SetZoomWindow(rcDst);
}

BOOL CVideoWindow::OnEraseBkgnd(CDC* pDC)
{
	CRect rect;
	//	this->GetClientRect(&rect);
	//	pDC->FillRect(&rect, &bkgndBrush);
	if (m_VideoWindow.GetSafeHwnd())
	{
		CDC * pVDC = m_VideoWindow.GetDC();
		CRect rect;
		m_VideoWindow.GetClientRect(&rect);
		pVDC->FillRect(&rect, &bkgndBrush);
		m_VideoWindow.ReleaseDC(pVDC);
	}
	dDraw.DDrawOnPaint();

	return TRUE;
	return CWnd::OnEraseBkgnd(pDC);
}

void CVideoWindow::OnPaint()
{
	CPaintDC dc(this); // device context for painting
	CRect rect;
	CDC * pDC;
	//	pDC = this->GetDC();
	//	this->GetClientRect(&rect);
	//	pDC->FillRect(&rect, &bkgndBrush);
	//	this->ReleaseDC(pDC);
	if (m_VideoWindow.GetSafeHwnd())
	{
		pDC = m_VideoWindow.GetDC();
		m_VideoWindow.GetClientRect(&rect);
		pDC->FillRect(&rect, &bkgndBrush);
		m_VideoWindow.ReleaseDC(pDC);
	}
	dDraw.DDrawOnPaint();
	
	if (m_VideoWindow.GetSafeHwnd() && m_strMsg.GetLength())
	{
		m_VideoWindow.GetClientRect(&rect);
		pDC = m_VideoWindow.GetDC();
		if (m_strMsg.GetLength())
		{
			HDC hDC = 0;
			hDC = pDC->GetSafeHdc();
			if (hDC)
			{
				int			bkmode = SetBkMode(hDC, TRANSPARENT);
				HFONT		font = NULL, pFont = NULL;

				COLORREF	col = SetTextColor(hDC, m_OSDColor);
				//COLORREF bkcol = SetBkColor(hDC, RGB(0,0,0));
				if (font = CreateFontIndirect(&m_OSDCenterFont))
					pFont = (HFONT)SelectObject(hDC, font);
				CRect tmpRect;
				tmpRect.left = rect.left;
				tmpRect.right = rect.right;
				tmpRect.top = rect.top + (rect.Height() / 2) - 30;
				tmpRect.bottom = tmpRect.top + 60;
				::DrawTextW(hDC, m_strMsg.GetString(), m_strMsg.GetLength(), &tmpRect, DT_CENTER | DT_VCENTER | DT_WORDBREAK);//DT_END_ELLIPSIS | DT_SINGLELINE | | DT_WORDBREAK

				//SetBkColor(hDC, bkcol);
				SetTextColor(hDC, col);
				SetBkMode(hDC, bkmode);
				if (pFont)
					SelectObject(hDC, pFont);
				if (font)
					DeleteObject(font);
			}
		}
		m_VideoWindow.ReleaseDC(pDC);
	}
	//DrawStatus();
}

int CVideoWindow::InitShareMemory(int i_index)
{
	m_nGetLength = 1;

	videoInIndex = i_index;
	if (m_hMapFileHeader == NULL)
		return -1;

	if (m_hMapFile == NULL)
		return -1;
	bool bExist = false;
	int i=0;
	for (i=0; i<MAX_DVR_CHANNEL; i++)
	{
		if (nvrVideoListIndexs[i] == NULL) continue;
		if (*(nvrVideoListIndexs[i]) == videoInIndex)
		{
			videoListIndex = i;
			bExist = true;
			break;
		}
	}

	if (!bExist || videoListIndex == -1)
	{
		__DEBUG("no exist dvr card\n");
		return -1;
	}

	nvrRawImage = m_nvrRawImageList[videoListIndex];
	if (nvrRawImage == NULL)
	{
		__DEBUG("nvrRawImage is NULL\n"); 
		return -1;
	}

	//	if (nvrRawImage->videoConnection == 0)
	//	{
	//		TRACE(L"Connection lost\n");
	//		return -1;
	//	}

	strcpy_s(videoInName, strlen(nvrRawImage->videoInName), nvrRawImage->videoInName);

	i_prev_atimestamp = 0;
	i_prev_vtimestamp = 0;

	//	if (nvrRawImage->width == 0 || nvrRawImage->height == 0)
	//	{
	//		return -1;
	//	}
	return 0;
}
void CVideoWindow::OnSnapshot(char* strFilePath)
{
}
void CVideoWindow::run()
{
	HANDLE hEvent;
	int nRet;
	int nCount = 0;
	__int64 next_vtimestamp;
	if (nvrRawImage == NULL) 
		return;
	hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
	DWORD i_prev_tick =::GetTickCount();
	DWORD i_tick = i_prev_tick;
	DWORD i_wait = 30;
	while(!needExit())
	{
		i_tick = ::GetTickCount();
		DWORD i_diff = i_tick - i_prev_tick;
		if (i_diff >= 30)
			i_wait = 0;
		else
			i_wait = 30 - i_diff;
		i_prev_tick = i_tick;

		nRet = ::WaitForSingleObject(hEvent, i_wait);
		i_prev_tick = ::GetTickCount();

		if (this->IsWindowVisible() == FALSE) 
		{
			Sleep(1);
			continue;
		}

		if (nRet != WAIT_TIMEOUT)
			break;

		if (needExit()) 
			break;

		next_vtimestamp  = nvrRawImage->vtimestamp;
		int i_data_size = nvrRawImage->image.length;
		Frame new_frame;
		new_frame.format = YUV_FORMAT::yuv_420;
		new_frame.height = nvrRawImage->height;
		new_frame.i_size = i_data_size;
		new_frame.strideY = nvrRawImage->width;
		new_frame.width = nvrRawImage->width;
		int connection = nvrRawImage->videoConnection;

		if (connection == 0)
		{
			m_nGetLength = 0;
			if (nCount++ > ((33 * 30)))
			{

			}
			continue;
		}
		if (i_prev_vtimestamp == next_vtimestamp) 
		{
			if ((nCount & 0x1f) == 0x1f)
			{
				__DEBUG("CVideoWindow::run() %d-%d cannot get image.", videoListIndex, videoInIndex);
//				CNVRGlobalInfoInstance::GetInstance()->LiveConnect(m_wndClientView, this);
			}
			if (nCount++ > ((33 * 30)))	//1 sec
			{
				m_nGetLength = 2;
				//TRACE(_T("dshow[%02d]: timestamp-x now %I64d prev %I64d tick=%d wait=%d\n"),videoInIndex, next_vtimestamp, i_prev_vtimestamp, i_tick, i_wait);
				__DEBUG("live[%d:%d]video loss now=%I64d prev=%I64d",
					videoListIndex, videoInIndex, next_vtimestamp, i_prev_vtimestamp);
			}
			continue;
		}

		if (new_frame.height == 0 || new_frame.width == 0) 
		{
			continue;
		}

		m_strMsg=_T("");
		//TRACE(_T("dshow[%02d]: timestamp now %I64d prev %I64d tick=%d wait=%d\n"),videoInIndex, next_vtimestamp, i_prev_vtimestamp, i_tick,i_wait);


		m_nGetLength = 3;


		nCount = 0;


		if (m_pRefImage == NULL) 
		{
			m_pRefImage = new BYTE[i_data_size];
			m_nBufferSize = i_data_size;
		} 
		else if (m_nBufferSize < i_data_size) 
		{
			delete[] m_pRefImage;
			m_pRefImage = new BYTE[i_data_size];
			m_nBufferSize = i_data_size;
		}

		memcpy(m_pRefImage, nvrRawImage->image.imageData , i_data_size);


		int total = new_frame.width * new_frame.height;
		new_frame.Y = m_pRefImage;
		new_frame.U = m_pRefImage + total;
		switch(nvrRawImage->imageFourCc)
		{
		case MAKEFOURCC('I','Y','U','V'):
		case MAKEFOURCC('I','4','2','0'):
		case MAKEFOURCC('Y','V','1','2'):
			new_frame.V = m_pRefImage + total + (total / 4);
			break;
		case MAKEFOURCC('Y','U','Y','2'):	//YUV422
			new_frame.V = m_pRefImage + total + (total / 2);
			break;
		}

		i_prev_vtimestamp = next_vtimestamp;

		//if (needPause() == true) continue;

		DrawFrame(&new_frame);
	}
	m_nGetLength = 0;
	CloseHandle(hEvent);
}

void CVideoWindow::DrawVideoLoss()
{
//	m_strMsg = CMessageMgm::GetInstance()->getMessage("MESSAGE_WARNING_VIDEO_LOSS");
} 

void CVideoWindow::DrawFrame(Frame* frame)
{
	//TRACE("draw frame\n");

	++i_frames;

	unsigned long t1 = ::GetTickCount();

	if (t1-t0 > 1000)
	{
		t0 = t1;
		prev_fps = i_frames;
		i_frames = 0;
	}

	i_img_width = frame->width;
	i_img_height = frame->height;

	PRESENTATION_ITEM pi;
	pi.Y = frame->Y;
	pi.U = frame->U;
	pi.V = frame->V;

	pi.i_data_len0 = frame->width;
	pi.i_data_len1 = frame->height;
	pi.i_data_len2 = frame->strideY;
	pi.i_other_data0 = (frame->format == yuv_420) ? 1 : 2;

	//var_bln_digitalzoom
	dDraw.BlitBitmap(&pi, TRUE);
}
void CVideoWindow::DrawIcons(HDC hDC, CRect &rect)
{
	
}
void CVideoWindow::stop()
{
	m_needPause = true;
	m_AudioClient.stop();
	m_strMsg = _T("");
	Runnable::stop();
	m_nQualityChange = 0;
	m_nNoTextOverlayForFullscreen = 0;
	m_bAudioSetting = FALSE;
	m_nGetLength = 5; m_stopPlayPauseStatue = 1;
	//m_bEnableDigitalZoom = FALSE;
	m_strRealTextoverlay = _T("");

	int getStatus = get_Length();
	if (getStatus != 8 && getStatus != 5 && getStatus != 0 && getStatus != 6)
	{
		//CNVRGlobalInfoInstance::GetInstance()->FileWriterLog(L" Vlcplugin stop() start call.");

		//CNVRGlobalInfoInstance::GetInstance()->FileWriterLog(L" Vlcplugin stop() end call.");
	}
	dDraw.CloseSurface();

}

void CVideoWindow::play()
{
	m_strMsg = _T("");
	t0 = ::GetTickCount();
	i_frames = 0;
	prev_fps = 0;
	m_needPause = false;
	int getStatus = get_Length();
	if (getStatus == 3)
	{
		return;
	}

	if (!ownerState)
	{
		//DrawVideoLoss();
		return;
	}
// 	if (IsBadReadPtr(ownerCameraInfo, 4))
// 	{
// 		stop();
// 		//DrawVideoLoss();
// 		return;
// 	}

// 	if ((m_kindLiveSearch == 0 && 
// 		(ownerCameraInfo->live == 0 || ownerCameraInfo->parentServer->rtspConnectStatus == 0)) 
// 		|| (m_kindLiveSearch == 1 && (ownerCameraInfo->search == 0 || !ownerCameraInfo->parentServer->dbInterfaceGP.IsConnectStatus())))
// 	{
// 		stop();
// 		//DrawVideoLoss();
// 		return;
// 	}
	/*
	if (m_currentUri == _T(""))
	return;

	for (int i=0; i<len; i++)
	{
	if (strDemux[i] == '/') //  localhost:8554/1/media.amp
	slashCount++;

	if (slashCount == 1)
	{
	if (strDemux[i] != '/')
	{
	strVideoInIndex[strlen(strVideoInIndex)] = strDemux[i];
	}
	}

	if (slashCount == 2 && len-i >= 9 && strncmp(strDemux+i, "media.amp", 9) == 0)
	{
	p_sys->b_dvr_card = true;
	break;
	}
	}
	*/

	if (!m_bPlayListNextFuncStatus)
		playlistNext();

	if (InitShareMemory(videoIndex) == -1)
	{
		stop();
		//DrawVideoLoss();
		return;
	}

	m_nGetLength=2; m_stopPlayPauseStatue = 2;
//	CNVRGlobalInfoInstance::GetInstance()->FileWriterLog(L" Vlcplugin Play() call.");
	m_strMsg = _T("");

	m_AudioClient.videoInIndex = videoInIndex;
	m_AudioClient.pAudioPlayer = m_pAudioPlayer;
	m_AudioClient.nvrRawImage = nvrRawImage;

	start();
}
bool CVideoWindow::needPause()
{
	return m_needPause;
}
void CVideoWindow::pause()
{
	m_AudioClient.stop();
	m_strMsg = _T("");
	m_needPause = true;
	Runnable::stop();
	int getStatus = get_Length();
	if (getStatus == 1 || getStatus == 2 || getStatus == 3)
	{
		if (!ownerState)
		{
			m_nGetLength = 4; m_stopPlayPauseStatue = 3;
			return;
		}

// 		if (IsBadReadPtr(ownerCameraInfo, 4))
// 		{
// 			m_nGetLength = 4; m_stopPlayPauseStatue = 3;
// 			stop();
// 			return;
// 		}

// 		if ((m_kindLiveSearch == 0 && ownerCameraInfo->live == 0) || (m_kindLiveSearch == 1 && ownerCameraInfo->search == 0))
// 		{
// 			m_nGetLength = 4; m_stopPlayPauseStatue = 3;
// 			stop();
// 			return;
// 		}

		if (m_kindLiveSearch == 1)
		{
			m_bAudioSetting = FALSE;
		}

//		CNVRGlobalInfoInstance::GetInstance()->FileWriterLog(L" Vlcplugin pause() call.");
	}

	dDraw.CloseSurface();

}

void CVideoWindow::setVariable(LPCTSTR name, VARIANT value)
{
	if (wcscmp(name, L"noVideoTextOverlay") == 0)
	{
		int codePage = CP_UTF8;
		m_strMsg = V_BSTR(&value);
		InvalidateRect(NULL, TRUE);
		//InvalidateRect(NULL, FALSE);
		return;
	}

	if (wcscmp(name, L"snapshot") == 0)
	{
		//var_TriggerCallback(p_vout, "video-snapshot");
		BSTR bstrVal = value.bstrVal;
		char c_Val[500];
		memset(c_Val, 0, sizeof(c_Val));
		int strSize = WideCharToMultiByte(CP_ACP, 0,value.bstrVal,-1, NULL, 0,NULL, NULL);
		WideCharToMultiByte(CP_ACP, 0, value.bstrVal, -1, c_Val, strSize, 0,0);
		OnSnapshot(c_Val);
		return;
	}

	if (wcscmp(name, L"frame") == 0)
	{
		//var_SetVoid(p_input, "frame-next");
		return ;
	}

	if (wcscmp(name, L"textoverlaystring") == 0)
	{
		//DrawStatus();
		BSTR bstrVal = value.bstrVal;
		char c_Val[500];
		memset(c_Val, 0, sizeof(c_Val));
		int strSize = WideCharToMultiByte(CP_ACP, 0,value.bstrVal,-1, NULL, 0,NULL, NULL);
		WideCharToMultiByte(CP_ACP, 0, value.bstrVal, -1, c_Val, strSize, 0,0);
		processStandardModeOverlay(value.bstrVal);
		return;
	}

	if (wcscmp(name, L"no_audio") == 0)
	{
		int i_value = V_I4(&value);
		if (i_value == 1)
		{
			m_AudioClient.stop();
		}
		else
		{
			if (isRuning()) m_AudioClient.start();
		}
		return;
	}

}
void CVideoWindow::processStandardModeOverlay(wchar_t *inputStr)
{
	
}

VARIANT CVideoWindow::getVariable(LPCTSTR name)
{
	VARIANT value;
	HRESULT hr = E_POINTER;
	VariantInit(&value);
	int codePage = CP_UTF8;
	hr = E_INVALIDARG;
	int i_type = 0;
	if (wcscmp(name, L"status") == 0)
	{
		V_VT(&value) = VT_I4;
		V_I4(&value) = var_int_status;
		return value;
	}

	if (wcscmp(name, L"noconnection") == 0)
	{
		V_VT(&value) = VT_BOOL;
		if (m_nGetLength == 0 || m_nGetLength == 2 || m_nGetLength == 3)
			V_BOOL(&value) =VARIANT_TRUE;
		else
			V_BOOL(&value) =VARIANT_FALSE;
		return value;
	}

	if (wcscmp(name, L"lowRes") == 0)
	{
		V_VT(&value) = VT_I4;
		V_I4(&value) = var_int_lowRes;
		return value;
	}

	if (wcscmp(name, L"liveConnectFlag") == 0)
	{
		V_VT(&value) = VT_I4;
		V_I4(&value) = this->isRuning() ? 1 : 3;
		return value;
	}

	return value;
}
void CVideoWindow::OnMButtonDblClk(UINT nFlags, CPoint point)
{
	CWnd::OnMButtonDblClk(nFlags, point);
}

void CVideoWindow::OnLButtonDblClk(UINT nFlags, CPoint point)
{	
	CWnd::OnLButtonDblClk(nFlags, point);
	m_nQualityChange = 0;
#if 1
//	CNVRGlobalInfoInstance::GetInstance()->DBClickActiveX(ownerNo, m_wndClientView);
#else
	CWnd * pParent = this->GetParent();
	int x, y;
	CRect rc;
	GetWindowRect(&rc);
	CPoint ptC;
	ptC = rc.CenterPoint();
	pParent->ScreenToClient(&ptC);
	LPARAM lParam = MAKELONG(ptC.x, ptC.y);
	pParent->PostMessage(WM_LBUTTONDBLCLK, 0, lParam);
#endif
}

void CVideoWindow::OnLButtonUp(UINT nFlags, CPoint point)
{
	if (m_bEnableDigitalZoom)
	{

	}
//	CNVRGlobalInfoInstance::GetInstance()->RedrawClientRect(ownerNo, m_wndClientView);
	CWnd::OnLButtonUp(nFlags, point);
}

void CVideoWindow::OnMouseMove(UINT nFlags, CPoint point)
{
	
	CWnd::OnMouseMove(nFlags, point);
}

BOOL	CVideoWindow::GetZoomWndRect(RECT * rcDst)
{
	RECT rect;
	m_VideoWindow.GetClientRect(&rect);
	RECT rcZoomWnd;
	int i_width = (CRect(rect).Width()) * 30 / 100;
	int i_height = (CRect(rect).Height()) * 40 / 100;

	int i_width_offset = (CRect(rect).Width()) / 22;
	int i_height_offset = (CRect(rect).Width()) / 20;

	rcZoomWnd.left = rect.right - i_width - i_width_offset;
	rcZoomWnd.top = rect.bottom - i_height - i_width_offset;
	rcZoomWnd.right = rect.right - i_width_offset;
	rcZoomWnd.bottom = rect.bottom - i_width_offset;

	m_VideoWindow.ClientToScreen(&rcZoomWnd);
	//m_rcZoomWnd = rcZoomWnd;
	*rcDst = rcZoomWnd;
	return TRUE;
}

void CVideoWindow::put_Volume(long newValue)
{
	if (newValue == 0 )
	{
		m_AudioClient.stop();
	}
	else
	{
		m_AudioClient.start();
	}

	int getStatus = get_Length();
	if (getStatus == 3 || getStatus == 4)
	{

	}
}

void CVideoWindow::OnTimer(UINT_PTR nIDEvent)
{
	if (nIDEvent == 0x100)
	{
		KillTimer(0x100);
		//DrawStatus();
		//SetTimer(0x100, 300, NULL);
	}

	__super::OnTimer(nIDEvent);
}

void CVideoWindow::DrawStatus()
{

}

int	CVideoWindow::GetAspectRatio()
{
	BOOL bRet = dDraw.IsFitSize();
	return bRet ? 0 : 1;
}

void CVideoWindow::SetAspectRatio(int nMode)
{
	if (nMode == 0)
	{
		dDraw.SetFitArea(TRUE);
	}
	else
	{
		dDraw.SetFitArea(FALSE);
	}

	CDC * pDC = m_VideoWindow.GetDC();
	CRect rect;
	this->GetClientRect(&rect);
	pDC->FillRect(&rect, &bkgndBrush);
	m_VideoWindow.ReleaseDC(pDC);
}

BEGIN_MESSAGE_MAP(CCustomWnd, CWnd)
	ON_WM_PAINT()
END_MESSAGE_MAP()

void CCustomWnd::OnPaint()
{
	CPaintDC dc(this); // device context for painting

}

void CVideoWindow::OnDestroy()
{
	__super::OnDestroy();

	// TODO: Add your message handler code here
}
